const leaveModel = require('../modules/leavemodules')
const moment = require('moment');
const xlsx= require ('node-xlsx');
const urlencode = require('urlencode');
const dateConfig=require('../config/dateconfig')
const excelConfig=require('../config/excelconfig')
const fs=require('fs')
const path =require('path');
class leaveController {
    
    /**
     * 根据登录名获取打卡时间
     * @param ctx
     * @returns {Promise.<void>}
     */
    static async getLeaveTimeByName(ctx) {
        //console.log(ctx.request.body);
        let req = ctx.request.body;
        let start = req.start;
        let end = req.end;
        let name = req.loginname;
        if (name) {
            try {
                let data = await leaveModel.getLeaveByLoginName(name,start,end);
                // console.log(data[0].dataValues);
                let result=new Array();
                for(let i=0;i<data.length;i++){
                   let o=data[i].dataValues;
                   let v=new Object();
                   v.DEFAULTDEPTID=o.DEFAULTDEPTID;
                   v.verifycode=o.verifycode;
                   v.title=moment(o.CHECKTIME).format('YYYY-MM-DD HH:mm:ss');//时分.format('YYYY-MM-DD HH:mm:ss')
                   v.start=moment(o.CHECKTIME).format('YYYY-MM-DD');//日期
                   //v.color="red";
                   if(moment(o.CHECKTIME).isBetween(`${dateConfig.summer.startDate}`,`${dateConfig.summer.endtDate}`)){
                       //夏令时
                        if(moment(o.CHECKTIME).isBetween(`${v.start} ${dateConfig.summer.startTime}`,`${v.start} ${dateConfig.summer.endTime}`))
                        {
                            v.textColor="red";
                        }else if(moment(o.CHECKTIME).isAfter(`${v.start} ${dateConfig.summer.overTime}`)){
                            v.textColor="green";
                        }
                        else{
                            v.textColor="black";
                        }       
                   }else{
                       //冬令时
                        if(moment(o.CHECKTIME).isBetween(`${v.start} ${dateConfig.winter.startTime}`,`${v.start} ${dateConfig.winter.endTime}`))
                        {
                            v.textColor="red";
                        }else if(moment(o.CHECKTIME).isAfter(`${v.start} ${dateConfig.winter.overTime}`)){
                            v.textColor="green";
                        }
                        else{
                            v.textColor="black";
                        }
                   }
                   v.allDay=true;
                   result.push(v);
                }
                //console.log(result);
                ctx.response.status = 200;
                ctx.body = {
                    code: 200,
                    msg: '查询成功',
                    data:result
                }

            } catch (err) {
                ctx.response.status = 412;
                ctx.body = {
                    code: 412,
                    msg: '查询失败',
                    err
                }
            }
        } else {
            ctx.response.status = 416;
            ctx.body = {
                code: 416,
                msg: '登录名必须传'
            }
        }
    }
    /**上传打卡记录 */
    static async uploadex(ctx){
        let req = ctx.req.body;
        if(ctx.req.file&&ctx.req.file.path){
            var str=ctx.req.file.path;
            req.iconUrl=str.substring(str.indexOf("\\"));
            await initdata(str,ctx);
            // ctx.response.status = 200;
            //     ctx.body = {
            //         code: 200,
            //         msg:'上传成功',
            //         data:''
            //     }
        }
    }
    /**导出报表 */
    static async exportex(ctx){
            let data= await checkModel.getUserByLoginName("郭祖容",'2018-12-29 00:00:00','2019-12-30 00:00:00');
            var arr=new Array();
            for(let i=0;i<data.length;i++){
                arr.push(data[i].dataValues)
            }
            exportExcel(ctx,excelConfig.checktime,arr,"dssd");
            ctx.response.status = 200;
    }
    
}
/**解析考勤Excel文件并且存到数据库 */
async function initdata(str,ctx) {
    var datajson = xlsx.parse(path.join(__dirname,'../')+`${str}`);
    var firstSheet = datajson[0].data;
    var insertval = new Array();
    if(firstSheet[2][0]=="主表ID_系统字段"&&firstSheet[2][1]=="姓名"
    &&firstSheet[2][2]=="部门"&&firstSheet[2][3]=="二级部门"&&firstSheet[2][4]=="工号"){
        //定义实体类数组
        var checktime = new Array('leaveid', 'Name', 'DEFAULTDEPTID', 'secondDEFAULTDEPTID', 'SSN', 'category', 'startTIME', 'endTIME','total');
        var res=new Array();
        for (var i = 3; i < firstSheet.length; i++) {
            let cdata = firstSheet[i];
            let odate = new Object();
            for (let j = 0; j < cdata.length; j++) {
                odate[checktime[j]] = cdata[j];
            }
            console.log(odate);
            insertval.push(odate)
            if (i % 1000 == 0) {
            let te= await leaveModel.createLeaves(insertval);
            res.push(te);
            insertval.splice(0, insertval.length)
            }

            //mcheckTimeModel.createCheckTime(odate);

        }
        await leaveModel.createLeaves(insertval);
        ctx.response.status = 200;
            ctx.body = {
                code: 200,
                msg:'上传成功',
                data:''
            }
    }else{
        ctx.response.status = 200;
        ctx.body = {
            code: 500,
            msg:'上传失败，文件格式有误',
            data:''
        } 
    }
}
/**导出Excel表格 */
async function exportExcel(ctx,config,listData,exclename){
    let excelConfig = [];
    excelConfig.push(config.map(item => {
        return item.title
    }))
    listData.forEach(list => {
        excelConfig.push(config.map(item => {
            //const value = list[item.column];
            return item.column!='CHECKTIME'?list[item.column]:moment(list[item.column]).format('YYYY-MM-DD HH:mm:ss');
        }))
    })
    console.log(excelConfig);
    let buffer = xlsx.build([{
        name: exclename,
        data: excelConfig
    }]);
    
    let name = urlencode(exclename + '_' + (+new Date()) + '.xlsx', "utf-8");;
    console.log(name);
    ctx.set('Content-Type', 'application/vnd.ms-excel;charset=UTF-8'); 
    ctx.set("Content-Disposition", "attachment; filename=" + name);
    // ctx.request.headers['user-agent'] 
    // ctx.setHaeder('Conten-Tyep', 'application/vnd.openxmmlformats:charset:s=utf-8');//设置响应头 
    // ctx.setHaeder('Conten-Disposition','attachment:filename="+encodeURLComponent("XXXXX")+".xlsx');//设置下载文件命名
    //fs.writeFileSync(path.join(__dirname,'../public/')+name,buffer,{ encoding: 'utf8', mode: 438 /*=0666*/, flag: 'w' })
    //console.log(buffer);
    //ctx.body = buffer;
    ctx.body = {
                code: 200,
                msg:'导出成功',
                data:buffer
                }

}

module.exports = leaveController